/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ugc.cnel.manabi.jpa;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import org.ugc.cnel.manabi.entidades.Inspeccion;
import java.util.ArrayList;
import java.util.Collection;
import org.ugc.cnel.manabi.bakenbeans.AuditBakenBean;
import org.ugc.cnel.manabi.bakenbeans.AuditBakenBean.tipomensaje;
import org.ugc.cnel.manabi.entidades.Inspector;
import org.ugc.cnel.manabi.jpa.exceptions.IllegalOrphanException;
import org.ugc.cnel.manabi.jpa.exceptions.NonexistentEntityException;
import org.ugc.cnel.manabi.jpa.exceptions.PreexistingEntityException;

/**
 *
 * @author Admin
 */
public class InspectorJpaController {

    public InspectorJpaController() {
        emf = Persistence.createEntityManagerFactory("UGC_CNELPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Inspector inspector) throws PreexistingEntityException, Exception {
        if (inspector.getInspeccionCollection() == null) {
            inspector.setInspeccionCollection(new ArrayList<Inspeccion>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<Inspeccion> attachedInspeccionCollection = new ArrayList<Inspeccion>();
            for (Inspeccion inspeccionCollectionInspeccionToAttach : inspector.getInspeccionCollection()) {
                inspeccionCollectionInspeccionToAttach = em.getReference(inspeccionCollectionInspeccionToAttach.getClass(), inspeccionCollectionInspeccionToAttach.getId());
                attachedInspeccionCollection.add(inspeccionCollectionInspeccionToAttach);
            }
            inspector.setInspeccionCollection(attachedInspeccionCollection);
            em.persist(inspector);
            for (Inspeccion inspeccionCollectionInspeccion : inspector.getInspeccionCollection()) {
                Inspector oldIdInspectorOfInspeccionCollectionInspeccion = inspeccionCollectionInspeccion.getIdInspector();
                inspeccionCollectionInspeccion.setIdInspector(inspector);
                inspeccionCollectionInspeccion = em.merge(inspeccionCollectionInspeccion);
                if (oldIdInspectorOfInspeccionCollectionInspeccion != null) {
                    oldIdInspectorOfInspeccionCollectionInspeccion.getInspeccionCollection().remove(inspeccionCollectionInspeccion);
                    oldIdInspectorOfInspeccionCollectionInspeccion = em.merge(oldIdInspectorOfInspeccionCollectionInspeccion);
                }
            }
            em.getTransaction().commit();
            AuditBakenBean.audit(tipomensaje.CREAR, "Creo un nuevo Inspector{" + inspector.getNombres() + " " + inspector.getApellidos() + "}");
        } catch (Exception ex) {
            if (findInspector(inspector.getId()) != null) {
                throw new PreexistingEntityException("Inspector " + inspector + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Inspector inspector) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Inspector persistentInspector = em.find(Inspector.class, inspector.getId());
            Collection<Inspeccion> inspeccionCollectionOld = persistentInspector.getInspeccionCollection();
            Collection<Inspeccion> inspeccionCollectionNew = inspector.getInspeccionCollection();
            List<String> illegalOrphanMessages = null;
            if (inspeccionCollectionNew != null) {
                for (Inspeccion inspeccionCollectionOldInspeccion : inspeccionCollectionOld) {
                    if (!inspeccionCollectionNew.contains(inspeccionCollectionOldInspeccion)) {
                        if (illegalOrphanMessages == null) {
                            illegalOrphanMessages = new ArrayList<String>();
                        }
                        illegalOrphanMessages.add("You must retain Inspeccion " + inspeccionCollectionOldInspeccion + " since its idInspector field is not nullable.");
                    }
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Inspeccion> attachedInspeccionCollectionNew = new ArrayList<Inspeccion>();
            if (inspeccionCollectionNew != null) {
                for (Inspeccion inspeccionCollectionNewInspeccionToAttach : inspeccionCollectionNew) {
                    inspeccionCollectionNewInspeccionToAttach = em.getReference(inspeccionCollectionNewInspeccionToAttach.getClass(), inspeccionCollectionNewInspeccionToAttach.getId());
                    attachedInspeccionCollectionNew.add(inspeccionCollectionNewInspeccionToAttach);
                }
            }
            inspeccionCollectionNew = attachedInspeccionCollectionNew;
            inspector.setInspeccionCollection(inspeccionCollectionNew);
            inspector = em.merge(inspector);
            for (Inspeccion inspeccionCollectionNewInspeccion : inspeccionCollectionNew) {
                if (!inspeccionCollectionOld.contains(inspeccionCollectionNewInspeccion)) {
                    Inspector oldIdInspectorOfInspeccionCollectionNewInspeccion = inspeccionCollectionNewInspeccion.getIdInspector();
                    inspeccionCollectionNewInspeccion.setIdInspector(inspector);
                    inspeccionCollectionNewInspeccion = em.merge(inspeccionCollectionNewInspeccion);
                    if (oldIdInspectorOfInspeccionCollectionNewInspeccion != null && !oldIdInspectorOfInspeccionCollectionNewInspeccion.equals(inspector)) {
                        oldIdInspectorOfInspeccionCollectionNewInspeccion.getInspeccionCollection().remove(inspeccionCollectionNewInspeccion);
                        oldIdInspectorOfInspeccionCollectionNewInspeccion = em.merge(oldIdInspectorOfInspeccionCollectionNewInspeccion);
                    }
                }
            }
            em.getTransaction().commit();
            AuditBakenBean.audit(tipomensaje.EDITAR, "Edito los datos del inspector{" + inspector.getNombres() + " " + inspector.getApellidos() + "}");
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = inspector.getId();
                if (findInspector(id) == null) {
                    throw new NonexistentEntityException("The inspector with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Inspector inspector;
            try {
                inspector = em.getReference(Inspector.class, id);
                inspector.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The inspector with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Inspeccion> inspeccionCollectionOrphanCheck = inspector.getInspeccionCollection();
            for (Inspeccion inspeccionCollectionOrphanCheckInspeccion : inspeccionCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Inspector (" + inspector + ") cannot be destroyed since the Inspeccion " + inspeccionCollectionOrphanCheckInspeccion + " in its inspeccionCollection field has a non-nullable idInspector field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(inspector);
            em.getTransaction().commit();
            AuditBakenBean.audit(tipomensaje.ELIMINAR, "Elimino el Inspector{" + inspector.getNombres() + " " + inspector.getApellidos() + "}");
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Inspector> findInspectorEntities() {
        return findInspectorEntities(true, -1, -1);
    }

    public List<Inspector> findInspectorEntities(int maxResults, int firstResult) {
        return findInspectorEntities(false, maxResults, firstResult);
    }

    private List<Inspector> findInspectorEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Inspector as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Inspector findInspector(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Inspector.class, id);
        } finally {
            em.close();
        }
    }

    public int getInspectorCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Inspector as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
}
